import mimetypes
import os
import smtplib
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


class EmailUtils:
    """
    邮件工具类，用于发送邮件通知
    """

    def __init__(self, smtp_server, smtp_port, email_user, email_password):
        """
        初始化邮件工具类

        Args:
            smtp_server (str): SMTP 服务器地址
            smtp_port (int): SMTP 服务器端口
            email_user (str): 发送邮件的邮箱地址
            email_password (str): 发送邮件的邮箱密码
        """
        self._smtp_server = smtp_server
        self._smtp_port = smtp_port
        self._email_user = email_user
        self._email_password = email_password

    def send_email_with_attachment(self, to, file_path, title="通知邮件", body=""):
        """
        发送带附件的邮件

        Args:
            to (str): 收件人邮箱地址
            file_path (str): 附件文件路径
            title (str, optional): 邮件标题. Defaults to "通知邮件".
            body (str, optional): 邮件正文. Defaults to "".
        """

        # 创建一个 MIMEMultipart 对象
        msg = MIMEMultipart()
        msg["From"] = self._email_user
        msg["To"] = to
        msg["Subject"] = title

        # 添加邮件正文
        msg.attach(MIMEText(body, "plain"))

        # 获取文件类型
        content_type, encoding = mimetypes.guess_type(file_path)
        if content_type is None or encoding is not None:
            content_type = 'application/octet-stream'

        # 打开附件文件
        with open(file_path, "rb") as attachment:
            # 创建 MIMEBase 对象
            main_type, sub_type = content_type.split('/', 1)
            part = MIMEBase(main_type, sub_type)
            part.set_payload(attachment.read())

            # 使用 base64 编码附件
            encoders.encode_base64(part)

            # 设置附件的文件名和 Content-Type
            part.add_header('content-disposition', 'attachment', filename = os.path.basename(file_path))
            part.add_header('Content-Type', content_type)

            # 将附件添加到邮件中
            msg.attach(part)

        try:
            # 连接 SMTP 服务器
            server = smtplib.SMTP(self._smtp_server, self._smtp_port)
            # server.starttls()  # 如果使用 TLS，则添加此行

            # 登录到邮箱
            server.login(self._email_user, self._email_password)

            # 发送邮件
            server.sendmail(self._email_user, to, msg.as_string())

            # 关闭连接
            server.quit()
            logging.info("邮件发送成功")
        except Exception as e:
            logging.info("邮件发送失败:", str(e))
